<template>
  <view>
    <view class="form-container">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" labelPosition="top">
        <cu-cell-group>
          <uni-forms-item name="workTime">
            <cu-cell
              title="时间"
              required
              link
              placeholder="选择时间"
              :description="formData.workTime"
              @click="showTimePicker"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="deptId">
            <cu-cell
              title="所属单位"
              required
              link
              placeholder="选择单位"
              :description="formData.deptName"
              @click="showDeptPicker"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="formId">
            <cu-cell
              title="装运物种"
              required
              link
              :description="formData.chemicalName"
              @click="showLoadPicker"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="formType">
            <cu-cell title="类型" required :description="formData.formTypeLabel" @click="showTypePicker" link>
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="frontLicensePlate">
            <cu-cell title="车头车牌" required>
              <input
                v-model="formData.frontLicensePlate"
                class="uni-input text-right"
                style="height: 100%"
                placeholder-class="placeholder__style"
                placeholder="请输入车头车牌"
                maxlength="10"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="rearLicensePlate">
            <cu-cell title="车尾车牌" required>
              <input
                v-model="formData.rearLicensePlate"
                class="uni-input text-right"
                style="height: 100%"
                placeholder-class="placeholder__style"
                placeholder="请输入车尾车牌"
                maxlength="10"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="nuclearWeigh">
            <cu-cell title="核载重量" required>
              <input
                type="number"
                v-model="formData.nuclearWeigh"
                class="uni-input text-right"
                style="height: 100%"
                placeholder-class="placeholder__style"
                placeholder="吨"
                maxlength="10"
              />
            </cu-cell>
          </uni-forms-item>
          <!--<uni-forms-item name="realWeight">
						<cu-cell title="实载重量" required>
							<input type="number" v-model="formData.realWeight" class="uni-input text-right"
								style="height: 100%;" placeholder-class="placeholder__style" placeholder="吨"
								maxlength="10" />
						</cu-cell>
					</uni-forms-item>-->
          <uni-forms-item name="checkSign">
            <cu-cell title="检查表" required link @click="handleCheckTable()">
              <image
                v-if="formData.checkSign"
                slot="default"
                class="icon-style"
                src="/static/images/notOverdueComplete.png"
                mode="aspectFill"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="processSign">
            <cu-cell title="程序表" required link @click="handleProcessTable()">
              <image
                v-if="formData.processSign"
                slot="default"
                class="icon-style"
                src="/static/images/notOverdueComplete.png"
                mode="aspectFill"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item>
            <cu-cell
              title="应急预案"
              description="查看"
              @click="handlePreview(formData.emergencyPlanFileUrl, 1)"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item>
            <cu-cell
              title="安全教育"
              description="查看"
              @click="handlePreview(formData.safetyEducationFileUrl, 2)"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="inspectPersonId">
            <cu-cell title="检查人" :description="formData.inspectPersonName" required></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="driverPersonType" required>
            <cu-cell
              title="驾驶员类型"
              :description="formData.driverPersonTypeName"
              required
              link
              @click="showDriverTypePicker"
            >
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="driverPersonName" v-if="formData.driverPersonType === '2'">
            <cu-cell title="驾驶员" required :description="formData.driverPersonName">
              <input
                v-model="formData.driverPersonName"
                class="uni-input text-right"
                style="height: 100%"
                placeholder-class="placeholder__style"
                placeholder="请输入"
                maxlength="10"
              />
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="driverPersonId" v-else>
            <cu-cell title="驾驶员" required link :description="formData.driverPersonName" @click="showDriverPicker">
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="supercargoPersonType" required>
            <cu-cell
              title="押运员类型"
              :description="formData.supercargoPersonTypeName"
              required
              link
              @click="showsupercargoPersonTypePicker"
            >
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="supercargoPersonName" v-if="formData.supercargoPersonType === '2'">
            <cu-cell title="押运员" required :description="formData.supercargoPersonName">
              <input
                v-model="formData.supercargoPersonName"
                class="uni-input text-right"
                style="height: 100%"
                placeholder-class="placeholder__style"
                placeholder="请输入"
                maxlength="10"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="supercargoPersonId" v-else>
            <cu-cell
              title="押运员"
              required
              link
              :description="formData.supercargoPersonName"
              @click="showsupercargoPersonPicker"
            >
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="confirmPersonId">
            <cu-cell title="确认人" required link :description="formData.confirmPersonName" @click="showConfirmPicker">
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="processPersonId">
            <cu-cell title="审核人" required link :description="formData.processPersonName" @click="showApprovePicker">
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
      </uni-forms>
    </view>
    <view class="submit-group">
      <button class="u-button-cancel" type="primary" :ripple="true" @click="submit">提交</button>
    </view>
    <CuDateTimePicker ref="timePicker" @change="timePickerChange" />
    <second-dept-picker ref="deptSelectorRef" @confirm="onDeptSelectorChange"></second-dept-picker>
    <load-category-picker ref="loadCategoryPicker" @confirm="loadCategoryPickerChange"></load-category-picker>
    <user-selector ref="driverPicker" @change="driverPickerChange"></user-selector>
    <user-selector ref="confirmPicker" @change="confirmPickerChange"></user-selector>
    <user-selector ref="approvePicker" @change="approvePickerChange"></user-selector>
    <data-picker
      ref="driveTypePicker"
      :data="driveTypeList"
      title="选择驾驶员类型"
      @confirm="driveTypePickerChange"
    ></data-picker>
    <data-picker ref="typePicker" :data="typeList" title="选择类型" @confirm="typePickerChange"></data-picker>
    <data-picker
      ref="supercargoPersonTypePicker"
      :data="driveTypeList"
      title="选择押运员类型"
      @confirm="supercargoPersonTypePickerChange"
    ></data-picker>
    <user-selector ref="supercargoPersonPicker" @change="supercargoPersonPickerChange"></user-selector>
  </view>
</template>

<script>
import dayjs from 'dayjs'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import DataPicker from '@/components/data-picker/index.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuDateTimePicker from '@/components/cu-date-time-picker/cu-date-time-picker.vue'
import userSelector from '@/components/user-selector/index.vue'
import DeptSelector from '@/components/dept-selector/index.vue'
import LoadCategoryPicker from './components/loadCategoryPicker.vue'
import SecondDeptPicker from './components/secondDeptPicker.vue'
import store from '@/store'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import {
  addLoadOperation,
  updateLoadOperation,
  getLoadOperationDetail,
  getFormDetail
} from '@/api/load-operation/add-load-operation.js'

export default {
  components: {
    CuCellGroup,
    CuCell,
    CuDateTimePicker,
    userSelector,
    DeptSelector,
    LoadCategoryPicker,
    CuRadioGroup,
    DataPicker,
    SecondDeptPicker
  },
  onLoad({ id }) {
    this.id = Number(id)
    if (id) {
      this.getDetail(id)
    }
  },
  data() {
    return {
      typeList: [],
      driveTypeList: [
        {
          value: '1',
          name: '内部'
        },
        {
          value: '2',
          name: '外部'
        }
      ],
      id: '',
      formData: {
        workTime: '',
        deptId: '',
        deptName: '',
        formTypeLabel: '',
        formId: '',
        formType: '',
        chemicalName: '',
        checkSign: '',
        processSign: '',
        inspectPersonName: store.getters.name,
        inspectPersonId: store.getters.staffId,
        driverPersonId: '',
        driverPersonName: '',
        processPersonId: '',
        processPersonName: '',
        supercargoPersonId: '',
        supercargoPersonName: '',
        confirmPersonId: '',
        confirmPersonName: '',
        driverPersonType: '',
        drivierPersonTypeName: '',
        supercargoPersonType: '',
        supercargoPersonTypeName: '',
        emergencyPlanFileUrl: '',
        safetyEducationFileUrl: ''
      },
      rules: {
        workTime: {
          rules: [
            {
              required: true,
              errorMessage: '时间不能为空'
            }
          ]
        },
        deptId: {
          rules: [
            {
              required: true,
              errorMessage: '单位不能为空'
            }
          ]
        },
        formId: {
          rules: [
            {
              required: true,
              errorMessage: '装运物种不能为空'
            }
          ]
        },
        formType: {
          rules: [
            {
              required: true,
              errorMessage: '类型不能为空'
            }
          ]
        },
        driverPersonId: {
          rules: [
            {
              required: true,
              errorMessage: '驾驶员不能为空'
            }
          ]
        },
        supercargoPersonId: {
          rules: [
            {
              required: true,
              errorMessage: '押运员不能为空'
            }
          ]
        },
        driverPersonName: {
          rules: [
            {
              required: true,
              errorMessage: '驾驶员不能为空'
            }
          ]
        },
        supercargoPersonName: {
          rules: [
            {
              required: true,
              errorMessage: '押运员不能为空'
            }
          ]
        },
        processPersonId: {
          rules: [
            {
              required: true,
              errorMessage: '审核人不能为空'
            }
          ]
        },
        confirmPersonId: {
          rules: [
            {
              required: true,
              errorMessage: '确认人不能为空'
            }
          ]
        },
        frontLicensePlate: {
          rules: [
            {
              required: true,
              errorMessage: '车头车牌不能为空'
            }
          ]
        },
        rearLicensePlate: {
          rules: [
            {
              required: true,
              errorMessage: '车尾车牌不能为空'
            }
          ]
        },
        realWeight: {
          rules: [
            {
              required: false,
              errorMessage: '实载重量不能为空'
            }
          ]
        },
        nuclearWeigh: {
          rules: [
            {
              required: true,
              errorMessage: '核载重量不能为空'
            }
          ]
        },
        checkSign: {
          rules: [
            {
              required: true,
              errorMessage: '检查表签名不能为空'
            }
          ]
        },
        processSign: {
          rules: [
            {
              required: true,
              errorMessage: '程序表签名不能为空'
            }
          ]
        }
      }
    }
  },
  methods: {
    showTimePicker() {
      this.$refs.timePicker.show()
    },
    timePickerChange(value) {
      this.formData.workTime = dayjs(this.value).format('YYYY-MM-DD HH:mm:ss')
    },
    showDeptPicker() {
      this.$refs.deptSelectorRef.open()
    },
    onDeptSelectorChange(obj) {
      this.formData.deptId = obj.value
      this.formData.deptName = obj.name
    },
    showLoadPicker() {
      if (this.id) {
        uni.showToast({
          icon: 'none',
          title: '无法修改装运物种'
        })
        return
      }
      this.$refs.loadCategoryPicker.open()
    },
    loadCategoryPickerChange(obj) {
      console.log(obj.formTypeLabel)
      this.typeList = []
      this.formData.chemicalName = obj.name
      this.formData.formId = obj.value
      this.formData.formTypeLabel = ''
      this.formData.formType = ''
      this.formData.checkSign = ''
      this.formData.processSign = ''
      this.formData.emergencyPlanFileUrl = ''
      this.formData.safetyEducationFileUrl = ''
      let formTypeLabel = obj.formTypeLabel.split(',')
      let formTypes = obj.formTypes.split(',')
      for (let i = 0; i < formTypeLabel.length; i++) {
        this.typeList.push({
          name: formTypeLabel[i],
          value: formTypes[i]
        })
      }
    },
    showDriverPicker() {
      if (!this.formData.driverPersonType) {
        uni.showToast({
          icon: 'none',
          title: '请先选择驾驶员类型'
        })
        return
      }
      this.$refs.driverPicker.open()
    },
    driverPickerChange(obj) {
      this.formData.driverPersonName = obj.name
      this.formData.driverPersonId = obj.value
    },
    showConfirmPicker() {
      this.$refs.confirmPicker.open()
    },
    confirmPickerChange(obj) {
      this.formData.confirmPersonName = obj.name
      this.formData.confirmPersonId = obj.value
    },
    showApprovePicker() {
      this.$refs.approvePicker.open()
    },
    approvePickerChange(obj) {
      this.formData.processPersonName = obj.name
      this.formData.processPersonId = obj.value
    },
    showTypePicker() {
      if (this.id) {
        uni.showToast({
          icon: 'none',
          title: '无法修改类型'
        })
        return
      }
      if (!this.formData.formId) {
        uni.showToast({
          icon: 'none',
          title: '请先选择装运物种'
        })
        return
      }
      this.$refs.typePicker.open()
    },
    async typePickerChange(obj) {
      this.formData.formType = obj.value
      this.formData.formTypeLabel = obj.name
      this.formData.checkSign = ''
      this.formData.processSign = ''
      let res = await getFormDetail({
        formType: this.formData.formType,
        formId: this.formData.formId
      })
      this.formData.emergencyPlanFileUrl = res.data.emergencyPlanFileUrl
      this.formData.safetyEducationFileUrl = res.data.safetyEducationFileUrl
      this.formData.formInfoId = res.data.formInfoId
    },
    showDriverTypePicker() {
      this.$refs.driveTypePicker.open()
    },
    driveTypePickerChange(obj) {
      this.formData.driverPersonId = ''
      this.formData.driverPersonName = ''
      this.formData.driverPersonType = obj.value
      this.formData.driverPersonTypeName = obj.name
    },
    showsupercargoPersonTypePicker() {
      this.$refs.supercargoPersonTypePicker.open()
    },
    supercargoPersonTypePickerChange(obj) {
      this.formData.supercargoPersonId = ''
      this.formData.supercargoPersonName = ''
      this.formData.supercargoPersonType = obj.value
      this.formData.supercargoPersonTypeName = obj.name
    },
    showsupercargoPersonPicker() {
      if (!this.formData.supercargoPersonType) {
        uni.showToast({
          icon: 'none',
          title: '请先选择押运员类型'
        })
        return
      }
      this.$refs.supercargoPersonPicker.open()
    },
    supercargoPersonPickerChange(obj) {
      this.formData.supercargoPersonId = obj.value
      this.formData.supercargoPersonName = obj.name
    },
    handlePreview(url, type) {
      if (!this.formData.formId || !this.formData.formType) {
        uni.showToast({
          icon: 'none',
          title: '请先选择装运物种和类型'
        })
        return
      }
      if (type === 1) {
        uni.navigateTo({
          url: `/pages/work/add-load-operation/task/ViewEmergency?url=${url}&readonly=true`
        })
      } else {
        uni.navigateTo({
          url: `/pages/work/add-load-operation/task/ViewSafety?url=${url}&readonly=true`
        })
      }
    },
    handleCheckTable() {
      if (!this.formData.formId || !this.formData.formType) {
        uni.showToast({
          icon: 'none',
          title: '请先选择装运物种和类型'
        })
        return
      }
      let that = this
      uni.navigateTo({
        url: `/pages/work/add-load-operation/checkTable?formId=${this.formData.formId}&formType=${this.formData.formType}&id=${this.id}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success:check': (data) => {
            console.log(data)
            if (data) {
              that.formData.checkSign = data.checkSign
              that.formData.createDockWorkProjectReqs = data.createDockWorkProjectReqs
            }
          }
        },
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('sendCheck', {
            checkSign: that.formData.checkSign,
            createDockWorkProjectReqs: that.formData.createDockWorkProjectReqs,
            id: that.id
          })
        }
      })
    },
    handleProcessTable() {
      if (!this.formData.formId || !this.formData.formType) {
        uni.showToast({
          icon: 'none',
          title: '请先选择装运物种和类型'
        })
        return
      }
      let that = this
      uni.navigateTo({
        url: `/pages/work/add-load-operation/processTable?formId=${this.formData.formId}&formType=${this.formData.formType}&id=${this.id}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success:process': (data) => {
            console.log(data)
            if (data) {
              that.formData.processSign = data.processSign
              that.formData.createDockWorkProcedureReqs = data.createDockWorkProcedureReqs
            }
          }
        },
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('sendProcess', {
            processSign: that.formData.processSign,
            createDockWorkProcedureReqs: that.formData.createDockWorkProcedureReqs,
            id: that.id
          })
        }
      })
    },
    async getDetail(id) {
      let res = await getLoadOperationDetail(id)
      let data = {
        ...res.data.dockWorkInfoResp
      }
      data.chemicalName = res.data.chemicalName
      data.formId = res.data.formId
      this.typeList = []
      let formTypeLabel = res.data.formTypeLabel.split(',')
      let formTypes = res.data.formTypes.split(',')
      for (let i = 0; i < formTypeLabel.length; i++) {
        this.typeList.push({
          name: formTypeLabel[i],
          value: formTypes[i]
        })
      }
      if (data.driverPersonId) {
        data.driverPersonTypeName = '内部'
        data.driverPersonType = '1'
      } else {
        data.driverPersonTypeName = '外部'
        data.driverPersonType = '2'
      }
      if (data.supercargoPersonId) {
        data.supercargoPersonTypeName = '内部'
        data.supercargoPersonType = '1'
      } else {
        data.supercargoPersonTypeName = '外部'
        data.supercargoPersonType = '2'
      }
      if (data.formType === '1') {
        data.emergencyPlanFileUrl = res.data.dockFormLoadingResp.emergencyPlanFileUrl
        data.safetyEducationFileUrl = res.data.dockFormLoadingResp.safetyEducationFileUrl
        data.createDockWorkProjectReqs = res.data.dockFormLoadingResp.inspectProjectResps
        for (let i of data.createDockWorkProjectReqs) {
          i.createProjectItemReqs = i.inspectProjectItemResps
        }
        data.createDockWorkProcedureReqs = res.data.dockFormLoadingResp.procedureResps
      } else {
        data.emergencyPlanFileUrl = res.data.dockFormUnloadResp.emergencyPlanFileUrl
        data.safetyEducationFileUrl = res.data.dockFormUnloadResp.safetyEducationFileUrl
        data.createDockWorkProjectReqs = res.data.dockFormUnloadResp.inspectProjectResps
        for (let i of data.createDockWorkProjectReqs) {
          i.createProjectItemReqs = i.inspectProjectItemResps
        }
        data.createDockWorkProcedureReqs = res.data.dockFormUnloadResp.procedureResps
      }
      data.checkSign = ''
      data.processSign = ''
      this.formData = data
    },
    async submit() {
      await this.$refs.form.validate()
      let createPersonSignReqs = [
        {
          signObject: '1',
          signUrl: this.formData.checkSign
        },
        {
          signObject: '2',
          signUrl: this.formData.processSign
        }
      ]
      this.formData.createPersonSignReqs = createPersonSignReqs
      if (!this.id) {
        await addLoadOperation({
          ...this.formData
        })
      } else {
        await updateLoadOperation({
          ...this.formData
        })
      }
      uni.showToast({
        title: '提交成功！',
        icon: 'success'
      })
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.icon-style {
  width: 46rpx;
  height: 46rpx;
}

.submit-group {
  background: #fff;
  z-index: 9;
  padding: 30px;
}

.form-container {
  margin-bottom: 200rpx;
}
</style>
